import Request from '@/libs/luch-request/index.js'
import {
	userInfo
} from '@/stores/userInfo.js';
import {
	sysConfig
} from '@/config';
import tool from '@/utils/tool.js';

export const apiBaseUrl = sysConfig.BaseUrl

const http = new Request()

http.setConfig((config) => {
	/* 设置全局配置 */
	config.baseURL = apiBaseUrl
	config.header = {
		...config.header,
	}
	return config
})

const info = userInfo();
//请求前拦截，用来动态加参,例如token
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	let time = Date.parse(new Date().toString()) / 1000;
	let utoken = '';
	if (info.token) {
		utoken = info.token
	}
	config.header = {
		...config.header,
		//'token':uni.getStorageSync('token')
		AccessToken: utoken,
		'Content-Type': 'application/json',
		timestamp: time,
		appId: sysConfig.APP_ID,
		Version: sysConfig.API_VERSION,
		sign: tool.bulidSign(time, config.data)
	}
	// console.log(config.url);


	// if (config.url == '/api/upload') {
	// 	config.header = {
	// 		'Content-Type': 'multipart/form-data',
	// 		AccessToken: utoken,
	// 		timestamp: time,
	// 		appId: sysConfig.APP_ID,
	// 		Version: sysConfig.API_VERSION,
	// 		sign: tool.bulidSign(time, config.data)
	// 	}
	// } else {
	// 	config.data = tool.crypto.AES.encrypt(JSON.stringify(config.data), sysConfig.APP_SECRET);
	// }

	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})



// 请求后
http.interceptors.response.use((response) => {
	console.log(response)

	if (response.data.code === 200) {
		if(response.config.url=='/api/upload'){
			uni.showToast({
				icon:"success",
				title:response.data.msg
			})
		}
		
		return response.data.data
	} else {
		return response.data.data
	}
	

}, (response) => {
	/*  对响应错误做点什么 （statusCode !== 200）*/
	// console.log(response)
	//未登录时清空缓存跳转
	if (response.statusCode === 401) {

		uni.clearStorageSync();
		var pages = getCurrentPages() // 获取栈实例
		// let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
		// uni.setStorageSync('pages', currentRoute);
		uni.reLaunch({
			url: '/pages/public/login'
		})
	}
	if(response.statusCode === 400){
		uni.showToast({
			icon:"error",
			title:response.data.msg
		})
	}
	return Promise.reject(response)
})

export default http
